/*
url: http://www.ronipl.com
author: Roni Pinili
2013 copyright
*/


$(window).load(function(){

	var docHeight = $(document).height();
	var winHeight = $(window).height();
	var winWidth = $(window).width();
	var divHeight = $(".content-section").height();
	var contentW =  $(".content-wrapper").height();			
	var headerWrapperHeight = $("#header-wrapper").outerHeight();

	$(".content-section").css("height", winHeight);	

		var navwrapperHeight = $("#nav").height();
		var centerNW = winHeight/2 - navwrapperHeight/2 
		$("#nav-wrapper").css("top",  centerNW);
		setTimeout (function(){
			$("#nav-wrapper").animate({ left:0}, 1500);
		}, 1000);
	function activeHome() {
		var home = $("#home").attr("id");
		if(home === home) {
			$("#one").addClass("active");
		}	
	}activeHome();
	
	
	var list = $("#nav li");
	 function scrollDivs(){
		$(list).click(function(e){
			e.preventDefault();
		 	var linkID = $(this).children("a").attr("href");
		 	$("html, body").animate({ 
		 		scrollTop: $(linkID).offset().top}, "slow");	
		});	 
	}scrollDivs();	

	
	function showTooltip() {
		$(list).hover(function(e){
			e.preventDefault();
			$(this).children("div").animate({ opacity: "show", left: 10 }, "fast")		
			},function(){
			$(this).children("div").animate({opacity: "hide", left: 0}, "fast")
		});
	}showTooltip();


	function workAnimate() {

		$.ajax({
			type: 'GET',
			url: 'gallerydata.xml',
			dataType: 'xml',
			success: function(gallery){
						
				$(gallery).find('featuredImages').each(function(){

			       var $featuredImages = $(this);
				   var title = $featuredImages.attr("title");
				   var project = $featuredImages.find('Project').text();
				   var company = $featuredImages.find('Company').text();
				   var role = $featuredImages.find('Role').text();
				   var linkUrl = $featuredImages.find('Url').text();
		           var imageurl = $featuredImages.attr('imageurl');

		           var html = '<li class="workL">';
		           html +='<div class="text-wrapper">' + project + '<br/>' + company + '<br/>' + role +  '<br/>' + linkUrl + '</div>';
		           html += '<img class="featured" alt=" '+ title +' " src="' + imageurl + '" />';
	       		   html += '</li>';

	       		    $('#portfolio ul.work-list').append($(html));
	       		   
				});
				
			   	 var listHeight = $(".work-list > li").height();
				 var textWrapperHeight = $(".text-wrapper").height();
				 var getlistHeight = listHeight - textWrapperHeight;
				
				 $(".work-list > li").mouseenter(function(){
				 	$(this).children('.text-wrapper').stop(false, false).animate({opacity:1, top: getlistHeight - textWrapperHeight});

				 }).mouseleave(function(){
				 	$(this).children('.text-wrapper').stop(false, false).animate({top: - textWrapperHeight + textWrapperHeight, opacity: 0})
				 
				 });		
			}

		});

	};

	
	sideMenu = $("#nav");
	sideMenuHeight = sideMenu.outerHeight();		
	menuItems = sideMenu.find("a");
	
	scrollItems = menuItems.map(function(){
		var item = $($(this).attr("href"));
		if (item.length) { return item; }

	});


	window.xmlLoaded = 0;
	$(window).scroll(function(){
		
		var fromTop = $(this).scrollTop()+sideMenuHeight;

		var cur  = scrollItems.map(function(){
			if($(this).offset().top < fromTop)
			return this;

	});

	cur = cur[cur.length-1];
	var id = cur && cur.length ? cur[0].id : "";
	
		 var lastId;
		if (lastId !== id) {
			lastId = id;
	 		
			menuItems
				.parent().removeClass("active")
			.end().filter("[href=#"+id+"]").parent().addClass("active");
			};

		
		var theID = id;
		var home = $("#home").attr("id");
		var roni = $("#roni").attr("id");
		var mail = $("#mail").attr("id");
		var port = $("#portfolio").attr("id");
		var navC = $ ("#nav");

		var  bgHomeScroll = $(".homebg").scrollTop();

		if (theID == home ) {
			$(".homebg").css({

			});
		}

		if (theID == port) {

			var workListItems = $(".work-list").children();
			 var eT =0;
			
			if(window.xmlLoaded == 0) {
				workAnimate();	
				window.xmlLoaded = 1;
			}

			 $(".workL").each(function(){
				 $(this).delay(eT).animate({
			 			opacity:1
				 	}, function(){
				 			$("#portfolio h2").delay(3500).animate({
				 				opacity:1
				 		});
				 	});
				eT +=500;

			 });				
		};	
		
		var childSkillset =  $(".skillset").children();
		eT = 0;
		var contentL =  $("#content-left");
		if (theID == roni ) {
			
			$(function(){
		
				$("#circle").fadeIn("fast");
				$("#x").animate({
					width:145,
					opacity:1
				},800, function(){
					$("#y").fadeIn().animate({
						height:50
					},500);
				});

				setTimeout(function(){	
					$(childSkillset).addClass("skill");
						$(".skill").each(function(){
						$(this).delay(eT).fadeIn();	
						eT  += 500;
					});
				},2000);

			setTimeout(function(){
				$("#circle-two").fadeIn("fast");
				$("#x2").fadeIn().animate({
						width:136
					},500, function(){
						$("#y2").fadeIn().animate({
					height:67
				}, 500)
					});
			},4000);	

			});		

			$(contentL).animate({
				left:0
			}, 800);

		};

		if (theID == mail) {
			
			setTimeout(function(){
			$("#form-wrapper").animate ({
				right:0
			}, 800);
			}, 800);
			
				$("#looking-forward").animate({
					left:0
				}, 800);
			
		};

		
		
	});


function modal(){

	

		var modalHeight = $("#modal-quick-mail").outerHeight();
		
		$("#modal-quick-mail").css({
			"position": "relative",
			"top": - winHeight/5
		});

		$(".em").click(function(){
			$(".overlay").fadeIn();
			$("#modal-quick-mail").fadeIn();
		});

		$("#closebtn").click(function(){
			$(".overlay").fadeOut();
			$("#modal-quick-mail").fadeOut();

		});
	}modal();

function quickMail(){

	$("<div/>", {
    'id':"err"
	}).insertBefore('#quick-mail');
	$('#submit').on('click', function(){
		
		var errors = [];
		var html = '<div class="error">';
		valid = true;
		$('#err').empty();

		function isValidEmailAddress(email) {
	    var pattern = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	    return pattern.test(email);
		};

		if( !isValidEmailAddress($('#email').val() || $('#email').val() == '') ) { 
			errors.push('* Please provide a valid email'  + '<br/>');
			valid = false;	
		}else {
			$('#email').blur(function(){
			$('.error').text('');
		});

		}

		
		if ($('#message').val() == '') {
			errors.push('* Please type something');
			valid = false;	
		}

		if(!valid) {
			html += errors.join('') + '</div>' + '<br/>'
			$('#err').append(html);
		}else {
			$('#err').hide();
			$.ajax({
	          type: 'POST',
	          url: 'actions/quickinquiry.php',
	          data: $('#quick-mail').serialize(),
	          beforeSend: function(){
	          	$("#submit").attr("disabled", "true")
	          	sending("Sending Message...")
	          },
	          success: function(success){
	            if(success == "Success!"){ 
	            	sendingSuccess("Your Message has been submitted!");
	            	returnHome()
	             
	            } else {
	            	sendingFailed("Error! Please try again later.");
	            	$("#submit").removeAttr("disabled");
	            }
	       	  }
	        });
		}

		return valid;
	});
}quickMail();



function contactMail(){

	$("<div/>", {
    'id':"errr"
	}).insertBefore('#form-wrapper');

	$('.submit').on('click', function(){

		var error = [];
		var html = '<div class="error">';
		valid = true;
		$('#errr').empty();	

		function isValidEmailAddress(emailContact) {
	    var pattern = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	    return pattern.test(emailContact);
		};

		if ($('#name').val() == '') {

			error.push('* Please enter your name'  + '<br/>');
			valid = false;	

		}

		if( !isValidEmailAddress($('#email-contact').val() || $('#email-contact').val() == '') ) { 
			error.push('* Please provide a valid email'  + '<br/>');
			valid = false;	
		}
	
		if ($('#message-contact').val() == '') {

			error.push('* Please type something'  + '<br/>');
			valid = false;	
		}

		if(!valid) {
			html += error.join('') + '</div>' + '<br/>'
			$('#errr').append(html);
		}else {
			
			$('#errr').hide();

			$.ajax({
	          type: 'POST',
	          url: 'actions/inquiry.php',
	          data: $('#sendEmail-form').serialize(),
	          beforeSend: function(){
	          	$(".submit").attr("disabled", "true")
	          	sending("Sending Message...")
	          },
	          success: function(success){
	            if(success == "Success!"){ 
	            	sendingSuccess("Your Message has been submitted!");
	            	returnHome()
	             
	            } else {
	            	sendingFailed("Error! Please try again later.");
	            	$(".submit").removeAttr("disabled");
	            }
	       	  }
	        });

		}

		return valid;

	});

}contactMail();

function returnHome(){
  setTimeout('window.location.href = "http://ronipl.com/"',2000);
}

$('<div/>', {
    'class': 'overlay'
  }).insertAfter('#form-wrapper');
  $('.overlay').append('<div class="notification"></div>');

  function sending(msg){
      $(".overlay").fadeIn();
      $(".notification").html(msg).fadeIn();
  }
  function sendingSuccess(msg){
      $(".notification").css('background', '#339900').html(msg).fadeIn();
      $(".overlay").delay(5000).fadeOut();
  }
  function sendingFailed(msg){
      $(".notification").html(msg).fadeIn();
      $(".overlay").delay(5000).fadeOut();

}

});


